package com.ypinkj.app.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ypinkj.app.annotation.UserLoginToken;
import com.ypinkj.app.entity.CCompany;
import com.ypinkj.app.entity.Dict;
import com.ypinkj.app.entity.User;
import com.ypinkj.app.mapper.UserMapper;
import com.ypinkj.app.sendmsg.SendMsg;
import com.ypinkj.app.service.TokenService;
import com.ypinkj.app.service.UserService;
import com.ypinkj.app.service.redis.RedisService;
import com.ypinkj.app.utils.MD5Util;
import com.ypinkj.app.utils.resultutils.Result;
import com.ypinkj.app.utils.resultutils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author jinbin
 * @date 2018-07-08 20:45
 */
@Api(tags = "个人")
@RestController
@RequestMapping("/")
public class UserApi {
    @Autowired
    UserService userService;
    @Autowired
    TokenService tokenService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    RedisService redisService ;

    //登录
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Object login( User user,String code){
        System.out.println("进入登录");
        //第一种登录方式   用户名+密码
        if (null==user.getPhone()){
            if (user!=null && user.getPassword()!=null) {
                //如果密码不为空则加密验证
                user.setPassword(MD5Util.string2MD5(user.getPassword()));
            }else {
                return ResultUtil.error(500,"密码不能为空");
            }
            //JSONObject jsonObject = new JSONObject();
            User userForBase = userService.findByUsername(user.getUsername());
            if(userForBase == null){
            /*jsonObject.put("message","登录失败,用户不存在");
            return jsonObject;*/
                return ResultUtil.error(500,"登录失败,用户不存在");
            }else {
                if (!userForBase.getPassword().equals(user.getPassword())){
                /*jsonObject.put("message","登录失败,密码错误");
                return jsonObject;*/
                    return ResultUtil.error(500,"登录失败,密码错误");
                }else {
                    String token = tokenService.getToken(userForBase);

                    //登陆成功更新用户token
                    userForBase.setToken(token);
                    userForBase.setUpdateTime(new Date());//登录时间
                    userForBase.setFirstLogin(userForBase.getFirstLogin()+1);
                    userService.UpdateUserToken(userForBase);
                    return ResultUtil.success(userForBase);
                }
            }
        }else {
            //第二种登录方式   手机号+验证码
            //判断手机号是否已注册
            User userByPhone = userService.findUserByPhone(user.getPhone());
            if(userByPhone == null){
                return ResultUtil.error(500,"登录失败,手机号不存在");
            }else {
                //获取redis中的手机号的验证码 code是表单提交的验证码
                String key = redisService.getValueByKey(userByPhone.getPhone());
                if (key!=null) {
                    //System.out.println(key+"=============="+code);
                    if (!key.equals(code)) {
                        return ResultUtil.error(500, "登录失败,验证码错误");
                    } else {
                        String token = tokenService.getToken(userByPhone);
                        //登陆成功更新用户token
                        userByPhone.setToken(token);
                        userByPhone.setUpdateTime(new Date());
                        userByPhone.setFirstLogin(userByPhone.getFirstLogin()+1);
                        userService.UpdateUserToken(userByPhone);
                        return ResultUtil.success(userByPhone);
                    }
                }else {
                    return ResultUtil.error(500, "验证码已失效,请重新获取");
                }
            }

        }
    }

    @ApiOperation(value = "发送手机验证码")
    @GetMapping("/getCode")
    public Result getCode(String phone) {
        //正则验证手机号
        String pattern="[1][3,4,5,6,7,8,9][0-9]{9}";
        if (!Pattern.matches(pattern, phone)){
            return ResultUtil.error(500,"手机号格式错误");
        }
        try {
            String code = SendMsg.SendCode(phone);
            //发送验证码成功时保存到redis中，过期时间600秒（10分钟）
            redisService.addKey(phone,code);
        }catch (Exception e){
            System.out.println(e);
            return ResultUtil.errorMsg();
        }

        return ResultUtil.success();
    }

    @ApiOperation(value = "注册用户")
    @PutMapping("/register")
    public Object reGister(User user,String code){
        if (user!=null&&user.getPassword()!=null) {
            String pattern="^[a-zA-Z0-9]{6,9}$";
            if (!Pattern.matches(pattern, user.getPassword())){
                return ResultUtil.error(500,"密码格式错误");
            }
            //如果密码不为空则加密验证
            user.setPassword(MD5Util.string2MD5(user.getPassword()));
        }else {
            return ResultUtil.error(500,"密码不能为空");
        }

        if (user.getPhone()==null){
            return ResultUtil.error(500,"手机号不能为空");
        }
        //判断手机号是否已注册
        User userPhone = userService.findUserByPhone(user.getPhone());
        if (userPhone!=null){
            return ResultUtil.error(500,"手机号已存在");
        }else {
            //正则验证手机号
            String pattern="[1][3,4,5,6,7,8,9][0-9]{9}";
            if (!Pattern.matches(pattern, user.getPhone())){
                return ResultUtil.error(500,"手机号格式错误");
            }
        }

        //获取redis中的手机号的验证码 code是表单提交的验证码
        String key = redisService.getValueByKey(user.getPhone());
        //System.out.println(key+"=============="+code);
        if (key==null) {
            return ResultUtil.error(500, "验证码已失效,请重新获取");
        }else {
            if (!key.equals(code)){
                return ResultUtil.error(500, "验证码不正确,请重新获取");
            }
        }

        User userForBase=userService.findByUsername(user.getUsername());
        //用户名6-12位字母+数字
        //密码6-9位数字+密码
        //手机号正则
        if(userForBase != null){
            return ResultUtil.error(500,"用户已存在");
        }else {
            //正则验证用户名
            String pattern="^[a-zA-Z0-9]{6,12}$";
            if (!Pattern.matches(pattern, user.getUsername())){
                return ResultUtil.error(500,"用户名格式错误");
            }
        }

        //默认用户状态为1
        user.setStatus(User.Status.VALID);
        user.setFirstLogin(0);
        //保存用户
        userMapper.insert(user);

        return ResultUtil.success();
    }


    /**
     * 需要拦截 @UserLoginToken 需要拦截
     * @return
     */
    @UserLoginToken
    @ApiOperation(value = "获取分页")
    @GetMapping("/getPageHelper")
    public PageInfo getPageHelper(){
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        //wrapper.like("username","1");
        List selectList = userMapper.selectList(wrapper);
        Page<Object> pageObject = PageHelper.startPage(1, 10);
        PageInfo<Dict> info = new PageInfo<>(selectList);
        System.out.println(info);
        return info;
    }

    @UserLoginToken
    @ApiOperation(value = "后台页面分页数据")
    @GetMapping("/getPageList")
    public Object getPageList(int page,int limit,User user){
        //设置分页参数
        PageHelper.startPage(page, limit);
        //查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (user.getUsername()!=null){
            queryWrapper.like(User::getUsername,user.getUsername());
        }
        if (user.getPhone()!=null){
            queryWrapper.like(User::getPhone,user.getPhone());
        }
        List selectList = userMapper.selectList(queryWrapper);
        PageInfo<User> info = new PageInfo<>(selectList);
        return ResultUtil.successCount(info.getList(),info.getTotal());
    }


    @UserLoginToken
    @ApiOperation(value = "列表")
    @GetMapping("/getUserList")
    public Result getUserList(){
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        //wrapper.like("username","1");
        List selectList = userMapper.selectList(wrapper);
        return ResultUtil.success(selectList);
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("/delete")
    public Object toLogin(String id){
        int i = userMapper.deleteById(id);
        if (i>0){
            return ResultUtil.success();
        }
        return ResultUtil.errorMsg();
    }

    //退出登录
    @ApiOperation(value = "个人用户退出登录",notes = "id:为当前用户id")
    @DeleteMapping
    public Result layout(String id){
        User company = new User();
        company.setToken("");
        company.setUpdateTime(new Date());
        company.setId(id);
        int i = userMapper.layout(company);
        return i>0 ? ResultUtil.success() : ResultUtil.errorMsg();
    }
}
